package com.word.rtf;

import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;

/**
 * 创建pdf的三种方式：word文档另存为rtf,wps另存为rtf，txt先设置编码为中文gb2312再另存为rtf。
 * 以上三种方式生成的rtf模板均可采用以下方法动态生成。
 * 
 * @author huyuehan
 */
public class RTFConvert {

    int inext = 0;

    public String strToRtf(String content) {

        char[] digital = "0123456789ABCDEF".toCharArray();
        StringBuffer sb = new StringBuffer("");
        byte[] bs;
        try {
            bs = content.getBytes("GB2312");// 此处读取的编码非常重要，如果不设置将会出现乱码
            int bit;
            for (int i = 0; i < bs.length; i++) {
                bit = (bs[i] & 0x0f0) >> 4;

                sb.append("\\'");
                sb.append(digital[bit]);
                bit = bs[i] & 0x0f;
                sb.append(digital[bit]);
            }
        }
        catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return sb.toString();

    }

    public String replaceRTF(String content, String markersign,
            String replacecontent) {
        String rc = strToRtf(replacecontent);
        String target = "";
        markersign = "$" + markersign + "$";
        target = content.replace(markersign, rc);
        return target;
    }

    @SuppressWarnings("rawtypes")
    public void rgModel(String inputPath, String outPath, HashMap data) {
        String sourname = inputPath + "\\" + "temp.rtf";
        String sourcecontent = "";
        InputStream ins = null;
        try {
            ins = new FileInputStream(sourname);
            byte[] b = new byte[1638400];// 提高对于RTF文件的读取速度，特别是对于1M以上的文件
            int bytesRead = 0;
            while (true) {
                bytesRead = ins.read(b, 0, 1638400);
                if (bytesRead == -1) {
                    System.out.println("读取模板文件结束");
                    break;
                }
                sourcecontent += new String(b, 0, bytesRead);
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        /* 修改变化部分 */
        String targetcontent = "";
        String oldText = "";
        Object newValue;
        /* 结果输出保存到文件 */
        try {
            Iterator keys = data.keySet().iterator();
            int keysfirst = 0;
            while (keys.hasNext()) {
                oldText = (String) keys.next();
                newValue = data.get(oldText);
                String newText = (String) newValue;
                inext = 0;
                if (keysfirst == 0) {
                    targetcontent = replaceRTF(sourcecontent, oldText, newText);
                    keysfirst = 1;
                }
                else {
                    targetcontent = replaceRTF(targetcontent, oldText, newText);
                    keysfirst = 1;
                }
            }

            FileWriter fw = new FileWriter(outPath, true);
            PrintWriter out = new PrintWriter(fw);
            if (targetcontent.equals("") || targetcontent == "") {
                out.println(sourcecontent);
            }
            else {
                out.println(targetcontent);
            }
            out.close();
            fw.close();
            System.out.println(outPath + " 生成文件成功");
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        SimpleDateFormat sdf = new java.text.SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss");
        Date current = new Date();
        String targetname = sdf.format(current).substring(0, 4) + "年";
        targetname += sdf.format(current).substring(5, 7) + "月";
        targetname += sdf.format(current).substring(8, 10) + "日";
        targetname += sdf.format(current).substring(11, 13) + "时";
        targetname += sdf.format(current).substring(14, 16) + "分";
        targetname += sdf.format(current).substring(17, 19) + "秒";
        targetname += ".doc";
        RTFConvert oRTF = new RTFConvert();

        // *****************************************
        // 利用HashMap读取数据库中的数据
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("name", "胡跃瀚");
        map.put("age", "26");
        map.put("sex", "男");

        oRTF.rgModel("E:\\rtf", "E:\\rtf\\" + targetname, map);

    }

}
